#include "HttpServer.hpp"
#include "Util.hpp"
#include <cstdlib>
#include <fstream>
#include<iostream>
#include <string>
#include <sys/socket.h>
#include <vector>
#include<memory>

#define ROOT "./wwwroot"
#define HOMEPAGE "index.html"

void HandlerHttpRequest(int sockfd)
{
    char buffer[1024];
    ssize_t s = recv(sockfd, buffer, sizeof(buffer) - 1, 0);
    if(s > 0){
        buffer[s] = 0;
    }
    std::vector<std::string>vline;
    Util::cutString(buffer, "\n", &vline);

    std::vector<std::string> vblock;
    //第一个参数就是所要切割的字符串
    Util::cutString(vline[0], " ", &vblock);

    std::string file = vblock[1];
    std::string target = ROOT;

    //为他设置一个默认的路径
    if(file == "/"){
        file = "index.html";
    }
    //这个target就是我们所要访问的资源文件
    target += file;
    std::cout<<target<<std::endl;

    std::string content;
    //这个文件输入流从选定文件处读取内容
    std::ifstream in(target);
    if(in.is_open()){
        std::string line;
        while(std::getline(in,line)){
            content += line;
        }
        in.close();
    }
    std::string HttpResponse;
    if(content.empty()){
        HttpResponse = "HTTP/1.1 404 NotFound\r\n";
    }
    else{
        HttpResponse = "HTTP/1.1 200 OK\r\n";
    }
    HttpResponse += "\r\n";
    HttpResponse += content;
    send(sockfd, HttpResponse.c_str(), HttpResponse.size(), 0);
}

int main(int argc,const char* argv[])
{
    if(argc != 2){
        exit(-1);
    }
    std::unique_ptr<HttpServer> httpserver(new HttpServer(atoi(argv[1]),HandlerHttpRequest));
    //让这个接口开始运行
    httpserver->Start();
    return 0;
}